package org.team4.service;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.team4.constants.SQLConstant;
import org.team4.constants.StringConstant;
import org.team4.dao.DAOFactory;
import org.team4.dao.SysMesUserDAO;
import org.team4.domain.SysMesUser;
import org.team4.exception.CRUDException;
import org.team4.util.LoginBean;
import org.team4.vo.Page;

import org.team4.service.IService;

@Service
public class SysMesUserService implements IService {

    private SysMesUserDAO sysMesUserDAO;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        sysMesUserDAO = (SysMesUserDAO) DAOFactory.getDAO(sessionFactory, SysMesUserDAO.class);
    }

    /**
     * 查找未读系统消息
     * 
     * @return
     * @throws CRUDException
     */
    public List<SysMesUser> findSysMessageByNoRead() throws CRUDException {
        return sysMesUserDAO.find(SQLConstant.SYSMESUSER_BY_READFLAG_HQL, StringConstant.FALSE, LoginBean.getLoginBean().getUser());
    }

    /**
     * 分页系统消息
     * 
     * @param page
     * @param readFlag
     * @return
     * @throws CRUDException
     */
    public Page<SysMesUser> listPagination(Page<SysMesUser> page, String readFlag) throws CRUDException {
        if (StringConstant.ALL.equals(readFlag))
            return sysMesUserDAO.pagination(page, SQLConstant.SYSMESUSER_PAGE_HQL, null, LoginBean.getLoginBean().getUser());
        else
            return sysMesUserDAO.pagination(page, SQLConstant.SYSMESUSER_BY_READFLAG_PAGE_HQL, null, readFlag, LoginBean.getLoginBean().getUser());
    }

    /**
     * 批量删除
     * 
     * @param idList
     * @throws CRUDException
     */
    public void delete(List<String> idList) throws CRUDException {
        sysMesUserDAO.deleteByIdList(idList);
    }

    /**
     * 清空系统消息
     * 
     * @throws CRUDException
     */
    public void deleteAll() throws CRUDException {
        sysMesUserDAO.deleteAll(sysMesUserDAO.find(SQLConstant.SYSMESUSER_ALL_HQL, LoginBean.getLoginBean().getUser()));
    }

    /**
     * 批量删除
     * 
     * @param idList
     * @throws CRUDException
     */
    public void updateReadFlag(List<String> idList) throws CRUDException {
        for (String id : idList) {
            SysMesUser smu = sysMesUserDAO.get(id);
            smu.setReadFlag(StringConstant.TRUE);
            sysMesUserDAO.update(smu);
        }
    }

    /**
     * 清空系统消息
     * 
     * @throws CRUDException
     */
    public void updateReadFlagAll() throws CRUDException {
        List<SysMesUser> smuList = sysMesUserDAO.find(SQLConstant.SYSMESUSER_ALL_HQL, LoginBean.getLoginBean().getUser());
        for (SysMesUser smu : smuList) {
            smu.setReadFlag(StringConstant.TRUE);
            sysMesUserDAO.update(smu);
        }
    }

}
